#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <sys/select.h>
#include "Log.hpp"
#include "Socket.hpp"

using namespace SocketModule;
using namespace LogModule;

#define NUM sizeof(fd_set) * 8
const int gdefaultfd = -1;
class SelectServer
{
public:
    SelectServer(int port)
        : _port(port), _listen_socket(std::make_unique<TcpSocket>()), _isrunning(false)
    {
    }
    void Init()
    {
        _listen_socket->BuildTcpSocketMethod(_port);
        for (int i = 0; i < NUM; i++)
            _fd_array[i] = gdefaultfd;
        // 添加listensockfd到辅助数组中
        _fd_array[0] = _listen_socket->Fd();
    }

    void Loop()
    {
        fd_set rfds; // read file descriptor set
        _isrunning = true;
        while (_isrunning)
        {
            // clear the file descriptor set rfds
            FD_ZERO(&rfds);
            struct timeval timeout{10, 0};
            int maxfd = gdefaultfd;
            // 将辅助数组中所有文件描述符添加到rfds中
            for (int i = 0; i < NUM; i++)
            {
                if (_fd_array[i] == gdefaultfd)
                    continue;
                // 合法的
                FD_SET(_fd_array[i], &rfds);
                maxfd = std::max(maxfd, _fd_array[i]);
            }

            // select负责就绪事件的检测
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, &timeout);
            switch (n)
            {
            case 0:
                std::cout << "select timeout" << std::endl;
                break;
            case -1:
                perror("select");
                break;
            default:
                // 有事件就绪了
                std::cout << "select event, remaining time: " << timeout.tv_sec << " seconds" << timeout.tv_usec << " microseconds" << std::endl;
                Distribute(rfds); //把已经就绪的sockfd，派发给指定的模块
                break;
            }
        }
        _isrunning = false;
    }
    void Accepter()
    {
        InetAddr client;
        // 有新的连接请求
        int newfd = _listen_socket->Accepter(&client); // 不会被阻塞，只执行"拷贝"
        if (newfd < 0)
            return;
        else
        {
            std::cout << "获得一个新的连接请求 " << newfd << " client info: " << client.Addr() << std::endl;
            // 将新连接的文件描述符添加到辅助数组中
            int pos = -1;
            for (int j = 0; j < NUM; j++)
            {
                if (_fd_array[j] == gdefaultfd)
                {
                    pos = j;
                    break;
                }
            }
            if (pos != -1)
            {
                _fd_array[pos] = newfd;
            }
            else
            {
                LOG(LogLevel::ERROR) << "服务器已经满了";
                close(newfd);
            }
        }
    }
    void Recver(int i)
    {
        // 合法的，就绪的，普通的fd
        // 这里的recv并不完善，需要协议才能解决
        char buffer[1024];
        ssize_t n = recv(_fd_array[i], buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client# " << buffer << std::endl;
            // 将收到的信息回显回去
            std::string message = "echo# ";
            message += buffer;
            send(_fd_array[i], message.c_str(), message.size(), 0);
        }
        else if (n == 0)
        {
            LOG(LogLevel::DEBUG) << "客户端退出, sockfd: " << _fd_array[i];
            close(_fd_array[i]);
            _fd_array[i] = gdefaultfd;
        }
        else
        {
            LOG(LogLevel::ERROR) << "客户端读取出错, sockfd: " << _fd_array[i];
            close(_fd_array[i]);
            _fd_array[i] = gdefaultfd;
        }
    }
    void Distribute(fd_set &rfds)
    {
        for (int i = 0; i < NUM; i++)
        {
            if (_fd_array[i] == gdefaultfd)
                continue;
            // 文件描述符是合法的了
            if (_fd_array[i] == _listen_socket->Fd())
            {
                if (FD_ISSET(_listen_socket->Fd(), &rfds))
                {
                    Accepter();
                }
            }
            // 不是listensockfd
            else
            {
                if(FD_ISSET(_fd_array[i], &rfds))
                {
                    Recver(i);
                }
            }
        }
    }
    ~SelectServer()
    {
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_socket;
    bool _isrunning;
    int _fd_array[NUM]; // 辅助数组，保存文件描述符
};